package com.vogue.api.common.security.granter;

import com.alibaba.fastjson.JSONObject;
import com.vogue.api.common.security.model.Oauth2User;
import com.vogue.api.common.security.model.UserInfo;
import com.vogue.api.common.security.service.Oauth2UserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

/**
 * 微信小程序登录
 */
public class WeChatMiniProgramTokenGranter  extends AbstractCustomTokenGranter {

    protected Oauth2UserDetailsService userDetailsService;

    public WeChatMiniProgramTokenGranter(Oauth2UserDetailsService userDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, "wechat_mini");
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected Oauth2User getCustomUser(Map<String, String> parameters) {
        logger.error("WeChatMiniProgramToken: "+ JSONObject.toJSON(parameters));
        //客户端提交的临时code  微信给的
        String code = parameters.get("code");
        UserInfo userInfo=JSONObject.parseObject(parameters.get("userInfo").toString(),UserInfo.class);
        return userDetailsService.miniProgramLogin(code,userInfo);
    }
}
